<?php

/**
 * Description of MenuItem
 *
 * Copyright (c) 2011 Tomáš Holub (tomas.holub@webadvice.cz)
 * 
 * @author Tomáš Holub (tomas.holub@webadvice.cz)
 * @package OverFishCMS
 */

namespace OverFish\Model\Repositories;

use OverFish\Model\Repository;

class MenuItem extends Repository {
    
    public function assignMenuItem($menuItemId, $pageId) {
        $items = $this->mapper->findBy(array("id_page", $pageId));
        
        foreach ($items as $item) {
            $item->setId_page(Null);
            $this->save($item);
        }
        
        $items = $this->mapper->findBy(array("id", $menuItemId));
        
        foreach ($items as $item) {
            $item->setId_page($pageId);
            $this->save($item);
        }
    }
    
    public function getTreeForGrid($menuId, $parent = Null, $level = 0) {
        $result = array();
        
        $items = $this->mapper->findByParentAndMenu($menuId, $parent);
        
        foreach ($items as $item) {
            $result[] = array(
                "level" => $level,
                "item" => $item,
            );
            
            $result = array_merge($result, $this->getTreeForGrid($menuId, $item->getId(), $level + 1));
        }
        
        return $result;
    }
    
    public function getTreeForSelect() {
        $result = array();
        
        $items = $this->mapper->findAllMenu();
        
        foreach ($items as $item) {
            $result[] = array(
                "title" => $item->title,
                "items" => $this->getTreeForGrid($item->id)
            );
        }  
            
        
        return $result;
    }
}

